from odoo import fields, models, api
from odoo.exceptions import UserError
import base64
import csv
from io import StringIO

province_city_county_selection = [('1', 'last'), ('3', 'level_1'), ('4', 'level_2'), ('5', 'level_3'), ('6', 'level_4'), ('7', 'level_5')]


class PEBackdoorTran(models.TransientModel):
    _name = 'pe.backdoor.tran'
    _description = "后门程序瞬态"
    _rec_name = "code"

    def _default_auto_code(self):
        records = self.env['pe.backdoor.tran'].search([])
        return "RPB" + str(len(records) + 1).zfill(3)

    code = fields.Char(string='索引码', default=_default_auto_code, index=True, copy=False, readonly=True)
    create_datetime = fields.Datetime(string='当前时间', default=fields.Datetime.now, copy=False, readonly=True)
    user_id = fields.Many2one(string='操作人', comodel_name='res.users', default=lambda self: self.env.user, copy=False, readonly=True)

    # 导入EXCEL文件
    # xlsx_data = fields.Binary('EXCEL/CSV文件')
    # xlsx_name = fields.Char('名称')

    # 导入CSV文件
    csv_data = fields.Binary('CSV文件')
    csv_name = fields.Char('名称')

    def read_csv(self):
        """
        读取csv
        @return csv_reader解析好的文件，headers表头
        """
        if self.csv_data:
            file_content = base64.b64decode(self.csv_data)
            file_content = StringIO(file_content.decode("utf-8"))
            csv_reader = csv.reader(file_content, delimiter=',')
            headers = next(csv_reader, None)  # 获取表头
            return csv_reader, headers
        else:
            raise UserError('请先上传必要的CSV文件！')

    def action_for_csv_import_postal_code(self):
        """ csv文件导入，获取邮编 """
        csv_reader, headers = self.read_csv()
        Deal1.csv_import_for_spain_postal_code(self.env, csv_reader, headers)
